#include "mapwidget.h"
#include "ui_mapwidget.h"
#include "databasemanager.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QGridLayout>
#include <QLabel>
#include <QPushButton>
#include <QFrame>
#include <QMessageBox>
#include "venuedetaildialog.h"
#include <QDebug>
#include "feedbackwidget.h"
#include <QSignalMapper>

mapwidget::mapwidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::mapwidget)
{
    ui->setupUi(this);

    // 尝试获取scrollAreaWidgetContents的QGridLayout布局
    QGridLayout *venueGridLayout = qobject_cast<QGridLayout*>(ui->scrollAreaWidgetContents->layout());
    if (!venueGridLayout) {
        qDebug() << "错误：scrollAreaWidgetContents 没有 QGridLayout！正在创建新的 QGridLayout";
        venueGridLayout = new QGridLayout(ui->scrollAreaWidgetContents);
        ui->scrollAreaWidgetContents->setLayout(venueGridLayout);
    }
    venueGridLayout->setHorizontalSpacing(1);   // 水平方向控件间距
    venueGridLayout->setVerticalSpacing(5);     // 垂直方向控件间距


    loadVenues();
}

mapwidget::~mapwidget()
{
    delete ui;
}

void mapwidget::handleDetailButtonClick(int venueId)
{
    showVenueDetail(venueId);
}

void mapwidget::loadVenues()
{
    if (!DatabaseManager::instance().getDatabase().isOpen()) {
        qDebug() << "场馆列表模块 (mapwidget)：数据库未打开，无法加载场馆列表。";
        return;
    }

    QGridLayout *venueGridLayout = qobject_cast<QGridLayout*>(ui->scrollAreaWidgetContents->layout());
    if (!venueGridLayout) {
        qDebug() << "loadVenues: scrollAreaWidgetContents 布局不是 QGridLayout";
        return;
    }

    // 清理旧控件和布局项
    QLayoutItem *item;
    while ((item = venueGridLayout->takeAt(0)) != nullptr) {
        if (item->widget()) {
            item->widget()->deleteLater();
        }
        delete item;
    }
    venues.clear();

    QSqlQuery query(DatabaseManager::instance().getDatabase());
    if (query.exec("SELECT venue_id, name, type, address, district, opening_hours, contact_info, introduction, ticket_info, latitude, longitude FROM Venues ORDER BY name;")) {
        int row = 0;
        int col = 0;
        while (query.next()) {
            VenueDetail venue;
            venue.venue_id = query.value("venue_id").toInt();
            venue.name = query.value("name").toString();
            venue.type = query.value("type").toString();
            venue.address = query.value("address").toString();
            venue.district = query.value("district").toString();
            venue.opening_hours = query.value("opening_hours").toString();
            venue.contact_info = query.value("contact_info").toString();
            venue.introduction = query.value("introduction").toString();
            venue.ticket_info = query.value("ticket_info").toString();
            venue.latitude = query.value("latitude").toDouble();
            venue.longitude = query.value("longitude").toDouble();
            venues.append(venue);

            QWidget* card = createVenueCard(venue);

            venueGridLayout->addWidget(card, row, col);

            col++;
            if (col >= 3) { // 每行两个卡片
                col = 0;
                row++;
            }
        }
        // 添加行列拉伸，让布局弹性更好
        venueGridLayout->setRowStretch(row + 1, 1);
        venueGridLayout->setColumnStretch(2, 1);
    } else {
        qDebug() << "场馆列表模块 (mapwidget)：查询场馆数据失败:" << query.lastError().text();
    }
}

QWidget* mapwidget::createVenueCard(const VenueDetail &venue)
{
    QFrame *cardFrame = new QFrame();
    cardFrame->setFixedSize(280, 150);
    // 用样式表定义蓝色边框和圆角
    cardFrame->setStyleSheet(R"(
        QFrame {
            background-color: white;
            border: 2px solid #3498db;  /* 蓝色边框 */
            border-radius: 10px;
        }
    )");

    QVBoxLayout *cardLayout = new QVBoxLayout(cardFrame);
    cardLayout->setContentsMargins(8, 8, 8, 8);
    cardLayout->setSpacing(5);

    QLabel *nameLabel = new QLabel("<b>" + venue.name + "</b>");
    nameLabel->setWordWrap(true);
    cardLayout->addWidget(nameLabel);

    QLabel *addressLabel = new QLabel("地址: " + venue.address);
    addressLabel->setWordWrap(true);
    cardLayout->addWidget(addressLabel);

    QLabel *hoursLabel = new QLabel("开放时间: " + venue.opening_hours);
    cardLayout->addWidget(hoursLabel);

    QPushButton *detailButton = new QPushButton("详情");
    detailButton->setFixedSize(80, 25);
    // 按钮蓝底白字样式
    detailButton->setStyleSheet(R"(
        QPushButton {
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 14px;
        }
        QPushButton:hover {
            background-color: #5dade2;
        }
        QPushButton:pressed {
            background-color: #2e86c1;
        }
    )");

    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addStretch();
    buttonLayout->addWidget(detailButton);
    cardLayout->addLayout(buttonLayout);

    // 信号映射，传递venue_id
    QSignalMapper *signalMapper = new QSignalMapper(this);
    connect(detailButton, SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(detailButton, venue.venue_id);
    connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(handleDetailButtonClick(int)));

    return cardFrame;
}


void mapwidget::onDetailButtonClicked()
{
    QPushButton *button = qobject_cast<QPushButton*>(sender());
    if (button) {
        int venueId = button->property("venueId").toInt();
        showVenueDetail(venueId);
    }
}

void mapwidget::showVenueDetail(int venueId)
{
    for (const auto &venue : venues) {
        if (venue.venue_id == venueId) {
            VenueDetailDialog dialog(venue, this);
            dialog.exec();
            return;
        }
    }
    QMessageBox::warning(this, "错误", "未找到场馆详情！");
}
